package com.turing.mission.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.turing.mission.commandLine.MyThread;
import com.turing.mission.entity.Mission;
import com.turing.mission.entity.MissionApply;
import com.turing.mission.feign.AuthService;
import com.turing.mission.feign.MerchantService;
import com.turing.mission.service.MissionApplyService;
import com.turing.mission.mapper.MissionApplyMapper;
import com.turing.mission.service.MissionService;
import enums.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import result.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
* @author dell
* @description 针对表【mission_apply(任务申请)】的数据库操作Service实现
* @createDate 2023-05-17 20:29:33
*/
@Service
public class MissionApplyServiceImpl extends ServiceImpl<MissionApplyMapper, MissionApply>
    implements MissionApplyService{

    @Resource
    private AuthService authService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantService merchantService;
    @Autowired
    private MissionService missionService;

    @Override
    public Result applySave(JSONObject jsonObject) {
        MissionApply missionApply = JSONObject.toJavaObject(jsonObject, MissionApply.class);
        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        System.out.println("token = " + token);
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject11 = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String cusId = jsonObject11.getString("username");

        //店主id
        Result merById = merchantService.getMerById(missionApply.getMerchantId());
        JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(merById.getData()));
        System.out.println("jsonObject2 = " + jsonObject2);
        //管理员id
        Result adminList = merchantService.adminList(missionApply.getMerchantId(), null, null, null, null, null, null);
        System.out.println("1"+adminList.getData());
        JSONObject object = (JSONObject) JSON.parse(JSON.toJSONString(adminList.getData()));
        JSONArray adminList1 = object.getJSONArray("adminList");
        System.out.println("adminList1 = " + adminList1);
        JSONObject keeper = object.getJSONObject("keeper");
        System.out.println("keeper = " + keeper);
        String id = keeper.getString("cusId");

        List<String> ids = new ArrayList<>();
        if(id != null){
            ids.add(id);
        }
        for (Object o : adminList1) {
            Map map = (Map) o;
            if(map.get("cusId") != null){
                ids.add(map.get("cusId").toString());
            }
        }
        if(ids.size() > 0){
            for (int i = 0; i < ids.size(); i++) {
                if(cusId.equals(id)){
                    missionApply.setMaId(UUID.randomUUID().toString());
                    missionApply.setCusId(cusId);
                    missionApply.setMaCreateTime(new Date());
                    missionApply.setMaState(0);
                    missionApply.setMissionTitle(missionApply.getMissionTitle()==null?jsonObject2.getString("merchantName").toString():missionApply.getMissionTitle());
                    int insert = this.baseMapper.insert(missionApply);
                    if(insert > 0){
                        return Result.success();
                    }
                    return Result.fail(ErrorCode.ERROR_ADD);
                }
            }
        }else {
            return Result.fail(3,"该商家无店主和管理员");
        }
        return Result.fail(2,"只有店主或者管理员可申请任务");
    }

    @Override
    public Result applyList(String merchantName, String loginAccount, Integer maState, Integer pageNum, Integer pageSize) {
        if (pageNum!=null && pageSize!=null){
            PageHelper.startPage(pageNum,pageSize);
        }
        List<Map> list = this.baseMapper.select(merchantName,loginAccount,maState,pageNum,pageSize);
        if(pageNum!=null && pageSize!=null){
            return Result.success(new PageInfo<>(list));
        }
        return Result.success(list);
    }

    @Override
    public Result getApplyById(String id) {
        Map map = this.baseMapper.getApplyById(id);
        if(map == null){
            return Result.fail(ErrorCode.NODATA);
        }
        return Result.success(map);
    }

    @Override
    public Result deleteByIds(String[] ids) {
        int i = this.baseMapper.deleteBatchIds(Arrays.asList(ids));
        if(i > 0 ){
            return Result.success();
        }
        return Result.fail(ErrorCode.ERROR_DELETE);
    }

    @Override
    public Result refuseApply(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        MissionApply missionApply = this.baseMapper.selectById(id);
        missionApply.setMaState(2);
        int i = this.baseMapper.updateById(missionApply);
        if(i > 0){
            return Result.success();
        }
        return Result.fail(ErrorCode.ERROR_EDIT);
    }

    @Override
    public Result missonSave(JSONObject jsonObject) {
        String maId = jsonObject.getString("maId");
        MissionApply missionApply = this.baseMapper.selectById(maId);
        if(missionApply.getMaState() == 1){
            return Result.fail(2,"该申请已处理");
        }
        if(missionApply.getMaState() == 2){
            return Result.fail(2,"该申请已被拒绝");
        }
        jsonObject.put("merchantId",missionApply.getMerchantId());
        //得到商家名
        Result merById = merchantService.getMerById(jsonObject.getString("merchantId"));
        JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(merById.getData()));
        jsonObject.put("leftAmount",jsonObject.getDouble("missionAmount"));
        jsonObject.put("missionState","P");
        jsonObject.put("missionTitle",jsonObject.getString("missionTitle")==null?jsonObject2.getString("merchantName").toString():jsonObject.getString("missionTitle"));
        jsonObject.put("sendState",0);

        //添加任务
        MyThread myThread = new MyThread(jsonObject,missionService);
        myThread.start();

        //修改审批申请
        missionApply.setMaState(1);
        int i = this.baseMapper.updateById(missionApply);
        if(i > 0){
            return Result.success();
        }
        return Result.fail(ErrorCode.ERROR_EDIT);
    }

}




